package com.nowcoder.community.utils;

import org.apache.commons.lang3.CharUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

@Component
public class SensitiveFilter {

    private static final Logger logger = LoggerFactory.getLogger(SensitiveFilter.class);

    //替换符
    private static final String REPLACEMENT = "***";

    //根节点
    private TrieNode root = new TrieNode();

    //当容器实例化这个bean后，即调用构造方法后，这个方法会自动调用
    @PostConstruct
    public void init() {
        //反射：读取过滤词文档，构造前缀树
        //getClass()：取得当前对象所属的Class对象
        //getClassLoader()：取得该Class对象的类装载器
        //类装载器负责从Java字符文件将字符流读入内存，并构造Class类对象，通过它可以得到一个文件的输入流
        try (
                InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("sensitive-words.txt");
                //字节流转为字符流
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        ) {
            String word = null;
            while ((word = reader.readLine()) != null) {
                //添加到前缀树中
                this.addKeyWord(word);
            }

        } catch (Exception e) {
            logger.error("加载敏感词文件失败: " + e.getMessage());
        }
    }

    /**
     * 构造前缀树
     *
     * @param word
     */
    private void addKeyWord(String word) {
        TrieNode tmp = root;
        for (int i = 0; i < word.length(); i++) {
            Character character = word.charAt(i);
            TrieNode sub = tmp.getSubNode(character);
            if (sub == null) {
                //初始化子节点加入
                sub = new TrieNode();
                tmp.addSubNode(character, sub);
            }
            //已有孩子
            //则tmp指针指向当前字符的节点
            tmp = sub;
            //是否已到结尾
            if (i == word.length() - 1) {
                tmp.setKeyWordEnd(true);
            }
        }
    }

    /**
     * 利用前缀树进行敏感词过滤
     *
     * @param text
     * @return
     */
    public String filter(String text) {
        if (StringUtils.isBlank(text)) {
            return null;
        }
        //指针1
        TrieNode tmp = root;
        //指针2
        int begin = 0;
        //指针3
        int end = 0;
        //结果
        StringBuilder sb = new StringBuilder();

        while ( begin < text.length() ) {
            char c = text.charAt(end);
            //跳过符号 如 $赌%%博$
            if (isStmbol(c)) {
                //如果当前指针1还是指向根节点，则指针2和指针3同时下移
                if (tmp == root) {
                    sb.append(c);
                    begin++;
                }
                end++;
                continue;
            }
            //检查下级节点
            tmp = tmp.getSubNode(c);
            if (tmp == null) {
                //以c开头的字符串不是敏感词
                sb.append(c);
                //指针3移动
                end++;
                begin++;
                //tmp又指向根
                tmp = root;
            } else if (tmp.isKeyWordEnd()) {
                //到了末尾
                sb.append(REPLACEMENT);
                end++;
                begin = end;
                tmp = root;
            } else {
                //检查下一个字符串
                if (end < text.length() - 1){
                    end++;
                }else {
                    //说明当前begin字符合法，但还需要判断begin下一个字符开头的
                    sb.append(text.charAt(begin));
                    begin++;
                    end = begin;
                    tmp = root;
                }
            }
        }

        return sb.toString();
    }


    //判断是否为符号
    private boolean isStmbol(Character c) {
        // 0x2E80~0x9FFF 是东亚文字范围
        return !CharUtils.isAsciiAlphanumeric(c) && (c < 0x2E80 || c > 0x9FFF);
    }


    //前缀树
    private class TrieNode {

        //关键词结束标记
        private boolean isKeyWordEnd = false;

        //子节点
        private Map<Character, TrieNode> subNode = new HashMap<>();


        private void addSubNode(Character c, TrieNode node) {
            subNode.put(c, node);
        }

        public TrieNode getSubNode(Character c) {
            return subNode.get(c);
        }

        public boolean isKeyWordEnd() {
            return isKeyWordEnd;
        }

        public void setKeyWordEnd(boolean keyWordEnd) {
            isKeyWordEnd = keyWordEnd;
        }
    }


}
